import 'package:flutter/material.dart';
import 'meishiCrad.dart';
import 'mealModel.dart';

class MeiShiTabBarView01 extends StatelessWidget {
  const MeiShiTabBarView01({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(children: [
      Row(
        children: [
          Expanded(child: CardVertical(meals[0])),
          Expanded(child: CardVertical(meals[1])),
        ],
      ),
      Row(
        children: [
          Expanded(child: CardHorizontal(meals[2], () {})),
        ],
      )
    ]));
  }
}

class MeiShiTabBarView02 extends StatefulWidget {
  MeiShiTabBarView02({Key? key}) : super(key: key);

  @override
  _MeiShiTabBarView02State createState() => _MeiShiTabBarView02State();
}

class _MeiShiTabBarView02State extends State<MeiShiTabBarView02>
    with AutomaticKeepAliveClientMixin<MeiShiTabBarView02> {
  // 设置一个数字表示最多存放几页的数据
  static const int allowPageNum = 3;
  // 原来只存放一页的数据，上拉下拉数据倒是对的，就是效果不好，多存放几页，效果很好
  List<int> page = [0];
  List<Meal> meals = <Meal>[];
  bool isLoading = false;
  late final ScrollController _controller = ScrollController();
  void _scrollListener() {
    if (isLoading == true) return; // 有时候如果滚动过快会多次调用监听器，需要屏蔽
    // 我是这么想的，如果向上取数据，就把位置往下移一点；如果向下取数据，就把位置向上一点
    final double jumpDistance =
        _controller.position.maxScrollExtent / allowPageNum;

    if (_controller.offset >= _controller.position.maxScrollExtent &&
        !_controller.position.outOfRange) {
      // 向下滚动
      // 先把spinner放上去
      setState(() {
        isLoading = true;
      });
      // 拿下一页的数据
      mealsForPage(page.last + 1).then((result) {
        setState(() {
          if (page.length >= allowPageNum) {
            page.removeAt(0);
            meals = meals.sublist(num_data_per_page);
            _controller
                .jumpTo(_controller.position.maxScrollExtent - jumpDistance);
          }
          page.add(page.last + 1);
          meals = [...meals, ...?result];
          isLoading = false;
        });
      }).catchError((e) {
        return;
      });
    }

    if (_controller.offset <= _controller.position.minScrollExtent &&
        !_controller.position.outOfRange) {
      // 向上滚动
      if (page.first == 0) return;
      // 先把spinner放上去
      setState(() {
        isLoading = true;
      });
      // 重新拿上一页的数据
      mealsForPage(page.first - 1).then((result) {
        setState(() {
          if (page.length >= allowPageNum) {
            page.removeLast();
            meals = meals.sublist(0, num_data_per_page * (allowPageNum - 1));
            _controller
                .jumpTo(_controller.position.minScrollExtent + jumpDistance);
          }
          page = [page.first - 1, ...page];
          meals = [...?result, ...meals];
          isLoading = false;
        });
      }).catchError((e) {
        return;
      });
    }
  }

  @override
  void initState() {
    super.initState();

    mealsForPage(page.first).then((result) {
      setState(() {
        meals = result; // 拿到第一页的数据
        //_controller = ScrollController(); // 生成一个滚动控制器
        _controller.addListener(_scrollListener); // 设置监听器
        //super.initState(); // 放到这里应该也合适
      });
    }).catchError((e) {
      return;
    });
  }

  Function like(Meal meal) {
    return () {
      setState(() {
        meal.isCollect = !meal.isCollect;
      });
    };
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView(
      controller: _controller,
      padding: EdgeInsets.all(6),
      children: [
        Container(
          height: isLoading ? 50.0 : 0,
          color: Colors.transparent,
          child: Center(
            child: new CircularProgressIndicator(),
          ),
        ),
        for (Meal meal in meals)
          Stack(
            alignment: Alignment.bottomLeft,
            children: [
              CardHorizontal(meal, like(meal)),
              Text("第$page页 第${meals.indexOf(meal) + 1}个 id:${meal.id}")
            ],
          ),
        Container(
          height: isLoading ? 50.0 : 0,
          color: Colors.transparent,
          child: Center(
            child: new CircularProgressIndicator(),
          ),
        ),
      ],
    );
  }
}
